"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : autocommit
Case Name   : 关闭自动提交，创建并调用存储过程，回滚/提交，另一个会话中查询
Create At   : 2023/01/17
@zou_jialiang0501162244
Description :
    1、兼容B库建表并插入数据
    2、创建包含自治事务的存储过程
    3、关闭自动提交，创建调用自治事务存储过程的普通存储过程，提交
    4、会话1：关闭自动提交，调用存储过程，查询表数据，回滚，再次查询表数据，调用存储过程，提交
    5、会话2：在会话1提交前后查询表数据
    6、清理环境
Expect      :
    1、成功
    2、执行成功
    3、执行成功
    4、执行成功，两次查询结果一致，2条数据
    5、两条数据，会话1提交后查询为3
    6、成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class TestAutocommit(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_autocommit_0038'
        self.procedure1 = 'p_autocommit_0038_1'
        self.procedure2 = 'p_autocommit_0038_2'
        self.db_name = 'db_autocommit_0038'
        self.log.info("-----预置兼容B库-----")
        preset_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility 'B';"
        preset_db_res = self.pri_sh.execut_db_sql(preset_db)
        self.log.info(preset_db_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, preset_db_res,
                      f"创建兼容B库失败")

    def test_autocommit(self):
        text1 = '-----step1:兼容B库建表并插入数据;expect:成功-----'
        self.log.info(text1)
        preset_tb = f"drop table if exists {self.tb_name};" \
                    f"create table {self.tb_name}(a int, b int);" \
                    f"insert into {self.tb_name} values(1, 2);"
        preset_res = self.pri_sh.execut_db_sql(preset_tb, dbname=self.db_name)
        self.log.info(preset_res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, preset_res,
                      f"建表失败: {text1}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, preset_res,
                      f"insert失败: {text1}")

        text2 = '-----step2:创建包含自治事务的存储过程;expect:执行成功-----'
        self.log.info(text2)
        sql1 = f'''create or replace procedure {self.procedure1}(a int,b int) 
        as
        declare
            num3 int := a;
            num4 int := b;
            pragma autonomous_transaction;
        begin
            insert into t_autocommit_0038 values(num3, num4);
        end; '''
        res = self.pri_sh.execut_db_sql(sql1, dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.CREATE_PROCEDURE_SUCCESS_MSG, res,
                      f"执行失败:{text2}")

        text3 = '-----step3:关闭自动提交，创建调用自治事务存储过程的' \
                '普通存储过程，提交;expect:执行成功-----'
        self.log.info(text3)
        sql2 = f'''set autocommit = 0;
        drop procedure if exists {self.procedure2};
        create or replace procedure {self.procedure2}(a int, b int) as
        declare
        begin
            insert into {self.tb_name} values(666, 666);
            {self.procedure1}(a, b);
            rollback;
        END;
        commit;
        '''
        res = self.pri_sh.execut_db_sql(sql2, dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, res, f"执行失败:{text3}")

        text4 = '-----step4:会话1关闭自动提交，调用存储过程，查询表数据，回滚，再次' \
                '查询表数据，调用存储过程，提交;expect:成功，两次查询结果一致，2条数据-----'
        self.log.info(text4)
        sql_cmd1 = f"set autocommit = 0;" \
                   f"select {self.procedure2}(11, 22);" \
                   f"select * from {self.tb_name} order by a;" \
                   f"rollback;" \
                   f"select * from {self.tb_name} order by a;" \
                   f"call {self.procedure2}(11, 22);" \
                   f"select pg_sleep(3);" \
                   f"commit;"
        session1 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql_cmd1, '', self.db_name))
        session1.setDaemon(True)
        session1.start()
        time.sleep(2)

        text5 = '-----step5:会话2查询表数据;expect:两条数据，会话1提交后查询为3-----'
        self.log.info(text5)
        sql_cmd2 = f"select * from {self.tb_name};" \
                   f"select pg_sleep(2);" \
                   f"select count(*) from {self.tb_name};"
        session2 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql_cmd2, '', self.db_name))
        session2.setDaemon(True)
        session2.start()
        session1.join(10)
        session2.join(10)
        res1 = session1.get_result()
        self.log.info(f'session1_results:\n {res1}')
        res2 = session2.get_result()
        self.log.info(f'session2_results:\n {res2}')
        self.assertIn('SET', res1, f"关闭自动提交失败: {text4}")
        self.assertEqual(res1.count(self.procedure2), 2, f"创建存储过程失败:{text4}")
        self.assertEqual(res1.count('1 |  2'), 2, f"执行失败: {text4}")
        self.assertEqual(res1.count('11 | 22'), 2, f"执行失败: {text4}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, res1, f"执行失败: {text4}")
        self.assertIn(self.constant.ROLLBACK_MSG, res1, f"执行失败: {text4}")
        self.assertIn('1 |  2', res2, f"执行失败: {text5}")
        self.assertEqual(res2.count('11 | 22'), 2, f"执行失败: {text5}")
        self.assertEqual(res2.splitlines()[-2].strip(), '3', f"执行失败: {text5}")

    def tearDown(self):
        text6 = '-----step6:清理环境 expect:成功-----'
        self.log.info(text6)
        drop_db_res = self.pri_sh.execut_db_sql(
            f"drop database if exists {self.db_name};")
        self.log.info(drop_db_res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_db_res,
                      f"执行失败: {text6}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
